package nix.anim.cms.interceptor;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import nix.anim.common.pojo.NixResult;
import nix.anim.pojo.User;
import nix.anim.sso.service.UserService;
import nix.anim.utils.CookieUtils;

/**
 * 用户登陆拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Value("${USER_SESSION_KEY}")
	private String USER_SESSION_KEY;
	
	/*@Value("${SSO_CONSOLE_DOMAIN}")
	private String SSO_CONSOLE_DOMAIN;*/
	
	@Autowired
	private UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		/* 执行handler之前执行此方法 返回true放行；返回false拦截 */	
		// 跨域验证的第一次请求
		if (request.getMethod().equals("OPTIONS")){
			response.setStatus(HttpServletResponse.SC_OK);
			return true;
		}
		// 从Cookie中取token
		//String token = CookieUtils.getCookieValue(request, USER_SESSION_KEY);
		String token = request.getHeader("token");
		// 取不到token，跳转sso登陆页，当前url作为参数传递，sso登陆成功后跳转回请求页面
		if (StringUtils.isBlank(token)) {
			// 取当前请求的url
			// String requestURL = request.getRequestURL().toString();
			// 跳转
			// response.sendRedirect(SSO_CONSOLE_DOMAIN + "/login.html?url=" + requestURL);
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			// 拦截			
			return false;
		}
		// 取到token，调用sso服务判断用户是否登陆
		NixResult result = userService.getUserByToken(token);
		// 如果未登录，跳转sso登陆页，当前url作为参数传递，sso登陆成功后跳转回请求页面
		if (result.getStatus() != 200) {
			// 取当前请求的url
			// String requestURL = request.getRequestURL().toString();		
			// 跳转
			// response.sendRedirect(SSO_CONSOLE_DOMAIN + "/login.html?url=" + requestURL);
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			// 拦截
			return false;
		}
		// 如果已登录，用户信息放入request，放行
		User user = (User) result.getData();
		request.setAttribute("currentUser", user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		/* handler执行之后，modelAndView返回之前，执行此方法 */

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		/* modelAndView返回之后，执行此方法 */
	}

}
